<?php
declare(strict_types=1);

namespace app\admin\controller;


use app\common\controller\Backend;
use quick\admin\annotation\AdminAuth;
use quick\admin\components\Component;
use quick\admin\http\response\JsonResponse;
use quick\admin\library\service\MenuService;
use quick\admin\library\service\NodeService;
use quick\admin\Quick;
use think\facade\Cache;


/**
 * Class Index
 * @AdminAuth(
 *     title="系统管理",
 *     auth=true,
 *     menu=true,
 *     login=false
 * )
 * @package app\admin\controller
 */
class Index extends Backend
{


    /**
     * @AdminAuth(auth=false,menu=false,login=false,title="Index")
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {

        $style = [
            'padding-left' => '20px',
            'padding-right' => '20px',
        ];

        $config = [
            'base' => request()->baseFile(),
            '_baseUrl' => '',
            'dashboard' => '/dashboard',
            'module' => "admin",// 多应用模块
            'layout' => "quick-layout",
//            'layout' => "scui-layout",
            'buyit' => false,// 显示右边弹出购买加群
            'show_logout' => true,//显示退出按钮
            'resources' => [],
            'actions' => [
                Component::action(Component::custom('div')
                    ->content('开发文档')->style($style))
                    ->openInNewTab('https://doc.quickadmin.cn'),
                Component::action(Component::custom('div')
                    ->content('个人中心')->style($style))
                    ->push('/admin/resource/admin_setting/index'),
            ],
            'rightActions' => [
                Component::custom('action-dropdown')->style([
                    'display' => 'table-cell',
                    'vertical-align' => 'baseline',
                    'font-size' => '16px'
                ])->props('actions', [
                    Component::action(Component::custom('div')
                        ->content('一键清除缓存')->style($style))
                        ->request('/admin/index/clearCache?type=all')

                ])->children(Component::icon('el-icon-Delete', '', '#333'), 'show'),
            ],
            'title' => sysConfig('app_name'),
            'appName' => sysConfig('app_name'),
            'appLogo' => sysConfig('app_logo'),
            'checkCaptcha' => $this->app->session->get("LoginCaptcha", false),
            'showCopyright' => true,
            'enableFullscreen' => true,
            'enablePageReload' => true,
            'copyrightDates' => sysConfig('copyrightDates') ?: '2020-2022',
            'loginBanner' => sysConfig('loginBanner') ?: "/assets/images/login-banner.jpg",
            'loginBgImage' => sysConfig('loginBgImage') ?: "/assets/images/login-bg.jpg",
            'copyrightCompany' => sysConfig('copyright'),
            'copyrightWebsite' => sysConfig('website'),

            /**
             *
             * 导航栏模式
             * side 侧边栏模式（含主导航）
             * head 顶部模式
             * single 侧边栏模式（无主导航）
             */
            "menuMode" => 'head',
        ];

        Quick::dispatchAssets();
        Quick::loadResource(["*"]);//注册资源
        Quick::provideToScript($config);

        return view('quick@quick/index', [
            'favicon' => '',
            'app_name' => sysConfig('app_name'),
            'base_url' => request()->baseFile() . '/' . app()->http->getName(),
            'assetsUrl' => request()->baseFile() . '/' . app()->http->getName(),
        ]);
    }

    /**
     * @AdminAuth(auth=false,menu=false,login=false,title="菜单")
     * @return \think\response\Json
     * @throws \ReflectionException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function test()
    {
        return view('quick@quick/test', []);
    }

    /**
     * @AdminAuth(auth=true,menu=true,login=true,title="菜单")
     * @return \think\response\Json
     * @throws \ReflectionException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function menu()
    {
        $methods = MenuService::instance();

        $menus = $methods->getTreeMenus("admin", false);


        $nodes = NodeService::instance()->getNodes();
        $app_name = app()->http->getName();
        $nodes = collect($nodes)->filter(function ($node) use ($app_name) {
            if ($app_name !== 'admin') {
                return $node['plugin_name'] === $app_name;
            }
            return true;
        })->map(function ($item) {
            return $item['title'];
        })->toArray();

        return json([
            'code' => 0,
            'data' => [
                'menus' => $menus,
                'nodes' => $nodes,
            ],
        ]);
    }

    /**
     * @AdminAuth(auth=true,menu=true,login=true,title="清除缓存")
     * @return \think\response\Json
     * @throws \Exception
     */
    public function clearCache()
    {
        Cache::clear();
        return JsonResponse::make()->success()->message('清除成功')->send();
    }


    /**
     * @AdminAuth(auth=true,menu=true,login=true,title="退出登录")
     * @return \think\response\Json
     * @throws \Exception
     */
    public function logout()
    {
        $auth = Quick::getAuthService();
        if ($auth->logout()) {
            return json([
                'code' => 0,
                'msg' => '注销成功',
            ]);
//            return redirect("login");
        }
        return json([
            'code' => 1,
            'msg' => '注销失败',
        ]);
    }

}
